//
//  MKAPIHttpRequestBase.m
//  MKAPI
//
//  Created by 苏尚进 on 2022/7/29.
//  Copyright © 2022 moon. All rights reserved.
//

#import "MKAPIHttpRequestBase.h"
#import "MKAPIPreCompile.h"
#import "NSObject+MKAPI.h"


@interface MKAPIHttpRequestBase()
@end
@implementation MKAPIHttpRequestBase
- (id)init{
    if (self=[super init]) {
    }
    return self;
}
- (NSString *)description{
    NSString *desc = [NSString stringWithFormat:@"<%@,requestType=%@,requestParam=%@>",[super description],@(self.requestType),self.requestParam];
    return desc;
}
- (NSURLRequest *)request{
    return _request;
}
- (NSHTTPURLResponse *)response{
    return _response;
}
- (NSData *)responseData{
    if(!_responseData){
        if(self.responseFile && [[NSFileManager defaultManager] fileExistsAtPath:self.responseFile.path]){
            _responseData = [NSData dataWithContentsOfURL:self.responseFile];
        }
    }
    return _responseData;
}
- (NSURL *)responseFile{
    return _responseFile;
}
+ (NSString *)requestDescriptionWithRequest:(nullable __kindof MKAPIHttpRequestBase *)request requestParam:(nullable __kindof MKAPIRequestParam *)requestParam customBlock:(NSString *(^_Nullable)(__kindof MKAPIHttpRequestBase *request))block{
    if(!requestParam){
        requestParam = request.requestParam;
    }
    NSMutableArray<NSString *> *desc = [[NSMutableArray alloc] initWithCapacity:5];
    [desc addObject:@"\n\
<{************************************************************\n\
*                       Request  Begin                       *\n\
**************************************************************\
"];
    [desc addObject:[NSString stringWithFormat:@"request %@ url:%@",requestParam.httpMethodString,requestParam.url]];
    [desc addObject:[NSString stringWithFormat:@"headers:%@",(request.request.allHTTPHeaderFields?:requestParam.headersParam.dictionary).mkapi_jsonString]];
    if(block){
        NSString *s = block(request);
        if(s){
            [desc addObject:s];
        }
    }else{
        do{
            if([requestParam isKindOfClass:[MKAPIRequestParamJSON class]]){
                MKAPIRequestParamJSON *jsonParam = requestParam;
                [desc addObject:[NSString stringWithFormat:@"JsonParam:%@",jsonParam.jsonParam.dictionary.mkapi_jsonString]];
                break;
            }
            if([requestParam isKindOfClass:[MKAPIRequestParamForm class]]){
                MKAPIRequestParamForm *formParam = requestParam;
                [desc addObject:[NSString stringWithFormat:@"formParam:%@",formParam.HTTPJsonFormBody.mkapi_jsonString]];
                break;
            }
            [desc addObject:[NSString stringWithFormat:@"requestParam:%@",requestParam.description]];
        }while(NO);
    }
    [desc addObject:@"\
**************************************************************\n\
*                        Request  End                        *\n\
************************************************************}>\n\
"];
    NSString *result = [desc componentsJoinedByString:@"\n"];
    return result;
}
+ (NSString *)responseDescriptionWithRequest:(nullable __kindof MKAPIHttpRequestBase *)request requestParam:(nullable __kindof MKAPIRequestParam *)requestParam customBlock:(NSString *(^_Nullable)(__kindof MKAPIHttpRequestBase *request))block{
    if(!requestParam){
        requestParam = request.requestParam;
    }
    NSMutableArray<NSString *> *desc = [[NSMutableArray alloc] initWithCapacity:5];
    [desc addObject:@"\n\
<{============================================================\n\
=                       Response Begin                       =\n\
==============================================================\
"];
    [desc addObject:[NSString stringWithFormat:@"response %@ url:%@",requestParam.httpMethodString,requestParam.url]];
    if(request.completedDate&&request.beginRunningDate){
        NSTimeInterval duration = [request.completedDate timeIntervalSinceDate:request.beginRunningDate];
        [desc addObject:[NSString stringWithFormat:@"Using:%.2f seconds",duration]];//耗时
    }
    if(request.response){
        [desc addObject:[NSString stringWithFormat:@"response data size:%@",[NSString mkapi_stringWithNSDataSize:request.responseData.length]]];
        [desc addObject:[NSString stringWithFormat:@"statusCode:%@",@(request.response.statusCode)]];
        [desc addObject:[NSString stringWithFormat:@"allHeaderFields:%@",request.response.allHeaderFields.mkapi_jsonString]];
        if(block){
            NSString *s = block(request);
            if(s){
                [desc addObject:s];
            }
        }else{
            do{
                id json = request.responseJson;
                if(json){
                    [desc addObject:[NSString stringWithFormat:@"responseJson:%@",[json mkapi_jsonString]]];
                    break;
                }
                NSString *responseString = request.responseString;
                if(responseString){
                    [desc addObject:[NSString stringWithFormat:@"responseString:%@",responseString]];
                    break;
                }
                UIImage *responseImage = request.responseImage;
                if(responseImage){
                    [desc addObject:[NSString stringWithFormat:@"responseImage:%@",responseImage]];
                    break;
                }
                if(request.responseFile){
                    [desc addObject:[NSString stringWithFormat:@"responseFile:%@",request.responseFile]];
                    break;
                }
                break;
            }while(NO);
            NSError *error = request.error;
            if(error){
                [desc addObject:[NSString stringWithFormat:@"error:%@",error]];
            }
        }
    }else{
        if(block){
            NSString *s = block(request);
            if(s){
                [desc addObject:s];
            }
        }else{
            NSError *error = request.error;
            if(error){
                [desc addObject:[NSString stringWithFormat:@"error:%@",error]];
            }
        }
    }
    [desc addObject:@"\
==============================================================\n\
=                        Response End                        =\n\
============================================================}>\n\
"];
    NSString *result = [desc componentsJoinedByString:@"\n"];
    return result;
}
@end
@implementation MKAPIHttpRequestBase (response)
- (NSString *)responseString{
    NSString *result = nil;
    if(self.responseData){
        result = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    }
    return result;
}
- (id)responseJson{
    NSError *error;
    id result = nil;
    if(self.responseData){
        result = [NSJSONSerialization JSONObjectWithData:self.responseData options:(NSJSONReadingOptions)0 error:&error];
    }
    if(!result&&self.responseFile&&[NSFileManager.defaultManager fileExistsAtPath:self.responseFile.path]){
        [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:self.responseFile] options:(NSJSONReadingOptions)0 error:&error];
    }
    return result;
}
- (NSDictionary *)responseJsonDict{
    NSDictionary *result = nil;
    id jsonObject = self.responseJson;
    if([jsonObject isKindOfClass:[NSDictionary class]]){
        result = (NSDictionary *)jsonObject;
    }
    return result;
}
- (NSArray *)responseJsonArray{
    NSArray *result = nil;
    id jsonObject = self.responseJson;
    if([jsonObject isKindOfClass:[NSDictionary class]]){
        result = (NSArray *)jsonObject;
    }
    return result;
}
- (UIImage *)responseImage{
    UIImage *result = nil;
    if (self.responseData) {
        result = [UIImage imageWithData:self.responseData];
    }
    return result;
}
@end
